package com.hsd.ha.app.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hsd.core.base.dao.IBaseDAO;
import com.hsd.core.base.service.impl.BaseService;
import com.hsd.core.page.Finder;
import com.hsd.core.page.entity.PageParams;
import com.hsd.core.page.entity.Pagination;
import com.hsd.core.utils.BigNumCal;
import com.hsd.ha.app.dao.IHealthAssessmentDao;
import com.hsd.ha.app.service.IHealthAssessmentService;
import com.hsd.ha.app.vo.FdtsVo;
import com.hsd.ha.app.vo.PhyVo;
import com.hsd.ha.cache.FdtsCache;

 
@SuppressWarnings("unchecked")
@Service
public class HealthAssessmentServiceImpl extends BaseService implements IHealthAssessmentService{
	@Autowired
	private IHealthAssessmentDao healthAssessmentDao;
	private  java.math.BigDecimal NUM_40 = new BigDecimal(40);
	private  java.math.BigDecimal NUM_25 = new BigDecimal(25);
	public void setHealthAssessmentDao(IHealthAssessmentDao healthAssessmentDao) {
		this.healthAssessmentDao = healthAssessmentDao;
	}
	public PhyVo calculatePhy(String phy_input){
		System.out.println("phy_input:" + phy_input);
		 PhyVo pvo = new PhyVo();
		 Map<String,Integer> dataMap = new HashMap<String, Integer>();
		 String tempInput = phy_input;
		 StringBuffer forward_phy = new StringBuffer();//倾向体质
		 StringBuffer both_phy = new StringBuffer();//兼有体质
 		 
		 int main_phy_value = 0;
		 int count_1_3 = 0;
		 int count_3_4 = 0;
		 int count_4 = 0;
		
		 String[] phy_arr = tempInput.split("\\|");
 		 for(int i=0;i<phy_arr.length;i++){
			 String temp = phy_arr[i]; 
			 String[] array = temp.split(":"); 
			 double dphy_value = BigNumCal.round(Double.parseDouble(array[1]), 0);
			 int phy_value = new Double(dphy_value).intValue();
			 String phy_code =  array[0];
			 if(!phy_code.equals("pinghezhi")){
				 if(phy_value < 30){
					 count_1_3++;
				  }else if(phy_value >= 30 && phy_value < 40){
					 count_3_4++;
					 forward_phy.append(phy_code).append(",");
				  }else{
					 count_4++; 
					 both_phy.append(phy_code).append(",");
				  }
				 dataMap.put(phy_code, new Integer(phy_value) );
			 } else{
				 main_phy_value = phy_value;
			 }
			// dataMap.put(phy_code, array[1]);
		 }
 		 System.out.println("count_1_3:" + count_1_3);
 		 System.out.println("count_3_4:" + count_3_4);
		 //判断是否为平和质
		 if(main_phy_value >= 60 ){ 
			 if(count_1_3 == 8){
				  pvo.setMain_phy("pinghezhi"); 
			 }else if((count_3_4+count_1_3) == 8){
				  pvo.setMain_phy("jibenpinghezhi"); 
			 }
		 }
		 if("".equals(pvo.getMain_phy())){
			 //"yangxuzhi:50|yinxuzhi:50|qixuzhi:50|tanshizhi:50|shirezhi:50|xuetanzhi:50|tebingzhi:50|qiyuzhi:50|pinghezhi:50"
			 int value  = (Integer)dataMap.get("qixuzhi").intValue();
			 System.out.println("value:" + value);
			 if( value >= 40){
				 pvo.setMain_phy("qixuzhi"); 
			 }
			 int value1  = (Integer)dataMap.get("yangxuzhi").intValue();
			 if( value1 >= 40){
				 pvo.setMain_phy("yangxuzhi"); 
			 }
			 int value2  = (Integer)dataMap.get("yinxuzhi").intValue();
			 if( value2 >= 40){
				 pvo.setMain_phy("yinxuzhi"); 
			 }
			 int value3 = (Integer)dataMap.get("tanshizhi").intValue();
			 if( value3 >= 40){
				 pvo.setMain_phy("tanshizhi"); 
			 }
			 int value4  = (Integer)dataMap.get("shirezhi").intValue();
			 if( value4 >= 40){
				 pvo.setMain_phy("shirezhi"); 
			 }
			 int value5  = (Integer)dataMap.get("xuetanzhi").intValue();
			 if( value5 >= 40){
				 pvo.setMain_phy("xuetanzhi"); 
			 }
			 int value6  = (Integer)dataMap.get("qiyuzhi").intValue();
			 if( value6 >= 40){
				 pvo.setMain_phy("qiyuzhi"); 
			 }
			 int value7  = (Integer)dataMap.get("tebingzhi").intValue();
			 if( value7 >= 40){
				 pvo.setMain_phy("tebingzhi"); 
			 }
		 }
		 
		 if("".equals(pvo.getMain_phy())){
			 pvo.setMain_phy("pinghezhi");
			 pvo.setForward_phy("");
			 pvo.setBoth_phy("");
		 }else{
			 pvo.setForward_phy(forward_phy.toString());
			 pvo.setBoth_phy(both_phy.toString());
			 System.out.println("count_1_3:" + count_1_3);
			 if(pvo.getBoth_phy().indexOf(pvo.getMain_phy())!=-1){
				 pvo.setBoth_phy(pvo.getBoth_phy().replace(pvo.getMain_phy()+",", ""));
			 } 
		 }
		 return pvo;
	 } 
	@Override
	public IBaseDAO getBaseDao() { 
		return healthAssessmentDao;
	}
	@Override
	public PhyVo calculatePhy(String phy_input, Map userinfo) {
		PhyVo phyObj = calculatePhy(phy_input);
		return phyObj;
	}
	public List loadHpListbyCode(String codestr){
		return this.healthAssessmentDao.loadHpList(codestr);
	}
	@Override
	public List loadHpListbyId(Long idstr) {
		// TODO Auto-generated method stub
		return this.healthAssessmentDao.loadHpList(idstr);
	}
	@Override
	public Pagination loadEvaDataList(PageParams pageParams, Map paramMap) { 
 			Finder finder = Finder.create("select  s");
			finder.append(" from HaSurveyInst s");
			finder.append(" where 1=1");
			String username = (String)paramMap.get("username");
			String startdate = (String)paramMap.get("startdate");
			String enddate = (String)paramMap.get("enddate");
			if(StringUtils.isNotEmpty(username)){
				finder.append(" and s.username like:username");
				finder.setParam("username", "%" + username + "%");
			}
			if(StringUtils.isNotEmpty(startdate)){
				finder.append(" and  DATE_FORMAT(s.surveydate,'%Y-%d-%m') >=").append(startdate);
			 
			}
			if(StringUtils.isNotEmpty(enddate)){
				finder.append(" and  DATE_FORMAT(s.surveydate,'%Y-%d-%m') <=").append(enddate);
			 
			}
			 
			Pagination page = healthAssessmentDao.find(finder, pageParams.getPageNo(), pageParams.getPageSize());
			return page; 
	} 
	@Override
	public String calculateFdtsResult(String fdts_input) { 
		//初始化所有的证型在一个map中，以证型的id为key
		Map allZxMap = null;
		String sexKey = "0";
		String num_key = "num_male";
		FdtsCache fdtsCache = FdtsCache.getInstance();
		JSONArray answerArray = JSONArray.fromObject(fdts_input);
		for(Object  qobj: answerArray){
			if(qobj instanceof JSONObject) {  
				JSONObject qanswer = (JSONObject)qobj;
				System.out.println("====>>> 答案对象  " + qanswer.toString());
				String databaseNo = qanswer.getString("databaseNo"); //数据库编号
	 			//获取性别
				if("0".equals(databaseNo)){
					JSONArray userObj =  qanswer.getJSONArray("answerArray");
					for(Object keyuser : userObj){
						sexKey = keyuser.toString();
					} 
					if("1".equals(sexKey)){
						num_key = "num_male";
					}else{
						num_key = "num_female";
					}
					allZxMap = initMap(num_key);
				} 
			}
			
		}
		
		for(Object obj : answerArray){
			if(obj instanceof JSONObject) {  
				JSONObject answer = (JSONObject)obj; 
				JSONArray answerObj =  answer.getJSONArray("answerArray");
				for(Object key : answerObj){
					String keyId = key.toString();
					System.out.println("答案编号   " + keyId); 
					List dataList = fdtsCache.getDataMapByAnswerid(keyId);
					if(null != dataList && dataList.size() >0){
						 for(int i = 0;i<dataList.size();i++){
							 Map dataConfig = (Map)dataList.get(i);
							 //System.out.println("dataConfig:"+dataConfig);
							 java.math.BigDecimal zxid = (BigDecimal)dataConfig.get("zxid");
							// System.out.println("zxid:"+zxid);
							 FdtsVo fv = (FdtsVo)allZxMap.get(zxid);
							// System.out.println("fv:"+fv);
							 java.math.BigDecimal  zxc_num = (BigDecimal )dataConfig.get(num_key);
							 System.out.println("zxc_num:" + zxc_num);
							 fv.add(zxc_num);
						 }
					}
				}
			}
		}  
//		 System.out.println("allZxMap:" + allZxMap);
		 Set resultset = allZxMap.entrySet();
		 Iterator iter = resultset.iterator();
		 FdtsVo  z_pinghe = new FdtsVo();//平和证型
		 FdtsVo  z_one = null;//一个证型
		 FdtsVo  z_two = null;//兼有证型
		 FdtsVo  z_three = null;//兼有证型
		 Set treeSet = new TreeSet();
		 System.out.println("排序开始:");
		 while(iter.hasNext()){
			 Entry entry = (Entry)iter.next();
			 FdtsVo fv = (FdtsVo)entry.getValue();
			 treeSet.add(fv);  
		 }
		 System.out.println("排序结果:"+treeSet);
		 Iterator iterset = treeSet.iterator();
		 int below_25 = 0;
		 while(iterset.hasNext()){
			 FdtsVo entry = (FdtsVo)iterset.next();
			 if(entry.getZx_num().compareTo(NUM_40) > 0){
				 z_one = entry;
				 break;
			 }else{
				 if(entry.getZx_num().compareTo(NUM_25) >= 0){
					  if(null == z_two ){
						  z_two = entry;
					  }else{
						  if(null == z_three ){
							  z_three = entry;
						  }else{
							  break;
						  }
					  }
				 }else{
					 below_25 ++;
				 }
			 }
		 }
		 //拼接结果
		 StringBuilder outstr = new StringBuilder();
		 outstr.append("<tr><tr><th valign='top'>您的证型为：</th><td><ul>");
		 if(null != z_one){
			 outstr.append("<li><a href=javascript: onclick=\"showZxDesc(").append(z_one.getZx_id()).append(");\">");
			 outstr.append(z_one.getZx_name());
			 outstr.append("</a></li>");
		 }else{
			 if(null != z_two || null !=z_three ){
				 if(null != z_two ){
					 outstr.append("<li><a href=javascript: onclick=\"showZxDesc(").append(z_two.getZx_id()).append(");\">");
					 outstr.append(z_two.getZx_name());
					 outstr.append("</a></li>");
				 }
				 if(null != z_three){
					 outstr.append("<li><a href=javascript: onclick=\"showZxDesc(").append(z_three.getZx_id()).append(");\">");
					 outstr.append(z_three.getZx_name());
					 outstr.append("</a></li>");
				 }
			 }else{
				 outstr.append("<li>");
				 outstr.append("阴阳平和");
				 outstr.append("</li>");
			 }
		 } 
		 outstr.append("</ul></td></tr>");
 
		 
		return outstr.toString();
	}
	private Map initMap(String key){
		List zxlist = FdtsCache.getInstance().getFdtsData();
		Map fvMap = new HashMap();
		
		for(int i = 0;i<zxlist.size();i++){
			  Map data = (Map)zxlist.get(i);
			  java.math.BigDecimal zxid = (BigDecimal)data.get("zxid");
			  java.math.BigDecimal qnum = (BigDecimal)data.get(key);
			  String zxmc = (String)data.get("zxmc");
			  FdtsVo fv = new FdtsVo();
			  fv.setZx_id(zxid);
			  fv.setZx_name(zxmc);
			  fv.setQnum(qnum.intValue());
			  fvMap.put(zxid, fv);
		}
		return fvMap;
	}
}